<template>
  <view class="my">
    <view class="my-item">
      <view class="my-item-tt tt1"></view>
      <view class="my-item-cont badge-wrap" v-if="succScenes.length < 3">
        <view :class="['badge badge1', { succ: succScenes.includes(1) }]"></view>
        <view :class="['badge badge2', { succ: succScenes.includes(2) }]"></view>
        <view :class="['badge badge3', { succ: succScenes.includes(3) }]"></view>
      </view>
      <view class="my-item-cont badge-wrap" v-if="succScenes.length === 3">
        <view class="badge badge4"></view>
      </view>
    </view>
    <view class="my-item">
      <view class="my-item-tt tt2"></view>
      <view class="my-item-cont cont2">
        <view class="my-prize-ps">
          <view class="animate-up">
            <view v-if="list.length" class="my-prize-ps-item" v-for="item in list" :key="item.text">
              {{ item.text }}
            </view>
            <view v-else class="my-prize-ps-item">暂无数据</view>
          </view>
        </view>
        <view class="my-prize-list">
          <view class="my-prize-item pr1" @click="choujiang(1)"></view>
        </view>
        <view class="my-prize-opp">今日剩余{{ prizeOpp }}次抽奖机会</view>
      </view>
    </view>
    <view class="my-item">
      <view class="my-item-tt tt3"></view>
      <view class="my-item-cont cont2">
        <view class="no-award">{{ myPrize }}</view>
        <view v-if="isAdmin" class="view-award-user" @click="viewUsers">查看中奖用户</view>
      </view>
    </view>


    <navbar defaultTab="my" />

    <nut-popup key="1" :style="{ background: 'transparent' }" pop-class="my-pop" :close-on-click-overlay="false"
      v-model:visible="showTip">
      <view class="my-tip-wrap">
        <view class="my-tip-tt"></view>
        <view class="my-tip">
          <view class="my-tip-txt">
            <view class="my-cong" v-if="myPrize === '未中奖'">{{ myPrize }}</view>
            <view class="my-cong" v-else>恭喜您中奖{{ myPrize }}</view>
          </view>
        </view>

        <view class="my-tip-btn" @click="closeTip"></view>
      </view>
    </nut-popup>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import Taro from "@tarojs/taro";
import navbar from '../home/navbar'
import { getDate, lottery, sum, getDateTime } from '../../utils'
import {
  sceneStateKey, sceneLen, weightSum, activeDateRange, prizeStateKey,
  userKey, prizes, phoneKey, adminPhones, prizesTotalNum, prizesNumsMap, prizeWeight
} from '../../constants'

const dateNow = getDate()
const succScenes = ref([])
const prizeOpp = ref(0)
const myPrize = ref('暂无奖品')
const isAdmin = ref(false)
const list = ref([])
const showTip = ref(false)

onMounted(async () => {
  const st = await Taro.getStorageSync(`${sceneStateKey}_${dateNow}`)
  succScenes.value = st?.succScenes ?? []

  const m = await Taro.getStorageSync(`${prizeStateKey}_${dateNow}`)
  if (![null, undefined, ''].includes(m.prizeOpp)) {
    prizeOpp.value = m.prizeOpp
  }
  const ph = await Taro.getStorageSync(phoneKey)
  if (ph) {
    isAdmin.value = adminPhones.includes(ph)
  }
  getAwards()
})

function viewUsers() {
  Taro.navigateTo({
    url: `/pages/setting/index`,
  });
}

function closeTip() {
  showTip.value = false
}

async function getAwards() {
  const phone = await Taro.getStorageSync(phoneKey)
  Taro.cloud.callFunction({
    name: 'getawards',
    success: res => {
      console.log(res);
      list.value = res.result.data?.map(t => ({
        ...t,
        text: `${t.phone?.slice(0, 3)}***${t.phone?.slice(-4)}中奖${t.award}`
      }))
      const hasAward = list.value.find(t => t.phone === phone)
      if (hasAward) {
        myPrize.value = hasAward.award
      }
      Taro.hideLoading()
    },
    fail: err => {
      Taro.hideLoading()
    }
  })
}

async function choujiang(type) {
  if (!prizeOpp.value) {
    Taro.showToast({
      title: '抽奖机会已用光',
      icon: 'none',
      duration: 2000
    })
    return
  }
  if (prizesNumsMap[myPrize.value]) {
    Taro.showToast({
      title: '您已中奖',
      icon: 'none',
      duration: 2000
    })
    return
  }
  const pw = [...prizeWeight]
  const overPrizes = []
  for (let i = 0; i < prizes.length; i++) {
    const k = prizes[i];
    const li = list.value.filter(t => t.createDate === dateNow && t.award === k)
    // 达到当天的奖品额度
    if (li.length >= prizesNumsMap[k]) {
      overPrizes.push(k)
      pw[i] = 0
    }
  }
  // 动态调整概率
  pw[pw.length - 1] = weightSum - sum(pw.slice(0, -1))
  if (overPrizes.length == Object.keys(prizesNumsMap).length) {
    Taro.showToast({
      title: '今天奖品池已抽空，请明天再来',
      icon: 'none',
      duration: 2000
    })
    return
  }
  const now = getDateTime();
  const startDate = activeDateRange[0];
  const endDate = activeDateRange[1];
  if (now < startDate) {
    Taro.showToast({
      title: '活动还未开始',
      icon: 'none',
      duration: 2000
    })
  } else if (now > endDate) {
    Taro.showToast({
      title: '活动已结束',
      icon: 'none',
      duration: 2000
    })
  } else {
    const res = lottery(weightSum, pw)
    myPrize.value = res.data
    prizeOpp.value = prizeOpp.value - 1
    showTip.value = true
    await Taro.setStorageSync(`${prizeStateKey}_${dateNow}`, {
      prizeOpp: prizeOpp.value,
      myPrize: myPrize.value
    })
    const phone = await Taro.getStorageSync(phoneKey)

    Taro.cloud.callFunction({
      name: 'countPlayers',
      data: {
        phone,
        type: 2,
        createDate: getDate()
      }
    })
    if (myPrize.value !== prizes[prizes.length - 1]) {
      const userInfo = await Taro.getStorageSync(userKey)
      Taro.cloud.callFunction({
        name: 'choujiang',
        data: {
          award: myPrize.value,
          createDate: getDate(),
          nickname: userInfo?.nickName,
          avatarUrl: userInfo?.avatarUrl,
          phone,
        },
        success: res => {
          getAwards()
          Taro.hideLoading()
        },
        fail: err => {
          Taro.hideLoading()
        }
      })
    }
  }
}
</script>

<style lang="scss">
.my {
  padding-top: 30px;
  padding-bottom: 120px;
  position: relative;
  width: 100vw;
  min-height: 110vh;
  box-sizing: border-box;
  background-image: url("https://7869-xiaofang-2g1dlrqbc66e0f24-1331027538.tcb.qcloud.la/award_img_bg.jpeg");
  background-size: 100% 100%;
  background-repeat: no-repeat;

}

.my-item-cont {
  box-sizing: border-box;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  margin: 10px 10px;
  height: 160px;
  background-image: url("https://7869-xiaofang-2g1dlrqbc66e0f24-1331027538.tcb.qcloud.la/award_img_box1.png");
  display: flex;
  align-items: center;
  justify-content: center;
}

.my-item-cont.cont2 {
  flex-direction: column;
}

.my-item-tt {
  box-sizing: border-box;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center;
  margin: 10px 80px;
  height: 60px;
  position: relative;
  top: 30px;
}

.my-item-tt.tt1 {
  background-image: url("https://7869-xiaofang-2g1dlrqbc66e0f24-1331027538.tcb.qcloud.la/award_img_title1.png");
}

.my-item-tt.tt2 {
  background-image: url("https://7869-xiaofang-2g1dlrqbc66e0f24-1331027538.tcb.qcloud.la/award_img_title2.png");
}

.my-item-tt.tt3 {
  background-image: url("https://7869-xiaofang-2g1dlrqbc66e0f24-1331027538.tcb.qcloud.la/award_img_title3.png");
}

.no-award {
  text-align: center;
  color: #606d73;
  font-weight: bold;
  font-style: italic;
}

.badge-wrap {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
}

.badge {
  width: 70px;
  height: 70px;
  box-sizing: border-box;
  background-size: contain;
  background-repeat: no-repeat;
  position: relative;
  opacity: 0.5;
}

.badge4,
.badge.succ {
  opacity: 1;
}

.badge1 {
  background-position: right;
  background-image: url("https://7869-xiaofang-2g1dlrqbc66e0f24-1331027538.tcb.qcloud.la/main_img_suipian1.png");
}

.badge2 {
  transform: rotate(90deg);
  background-position: center;
  background-image: url("https://7869-xiaofang-2g1dlrqbc66e0f24-1331027538.tcb.qcloud.la/main_img_suipian2.png");
}

.badge3 {
  background-image: url("https://7869-xiaofang-2g1dlrqbc66e0f24-1331027538.tcb.qcloud.la/main_img_suipian3.png");
}

.badge4 {
  background-image: url("https://7869-xiaofang-2g1dlrqbc66e0f24-1331027538.tcb.qcloud.la/award_img_allhuiz.png");
}

.animate-up {
  // transition: all 2s ease-in-out;
  // transform: translateY(-22px);
  animation: scroll-up 8s linear infinite;
}


@keyframes scroll-up {
  0% {
    transform: translateY(0);
  }

  100% {
    transform: translateY(-88px);
  }
}

.my-prize-ps {
  overflow: hidden;
  border-radius: 50px;
  background: linear-gradient(to right, #4EBE32, #dffcff);
  width: 180px;
  height: 22px;
  font-size: 14px;
  margin-top: 10px;
}

.my-prize-ps-item {
  width: 100%;
  height: 22px;
  text-align: center;
  line-height: 22px;
  color: #606d73;
}

.my-prize-list {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 60%;
  margin-top: 5px;
}

.my-prize-item {
  width: 138px;
  height: 45px;
  box-sizing: border-box;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  position: relative;
}

.my-prize-item.pr1 {
  background-image: url("https://7869-xiaofang-2g1dlrqbc66e0f24-1331027538.tcb.qcloud.la/start_lot.jpg");
}

.my-prize-opp {
  font-size: 14px;
  margin-top: 5px;
  color: #606d73;
}

.view-award-user {
  margin-top: 15px;
  color: #ecc114;
  font-size: 14px;
}

.my-tip-wrap {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: transparent
}

.my-tip {
  background-image: url("https://7869-xiaofang-2g1dlrqbc66e0f24-1331027538.tcb.qcloud.la/rule_img_smallbg.jpg");
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
  text-align: center;
  width: 350px;
  height: 330px;
  margin: 0 auto;
  display: flex;
  align-items: center;
  justify-content: center
}

.my-tip-btn {
  width: 174px;
  height: 55px;
  background-image: url("https://7869-xiaofang-2g1dlrqbc66e0f24-1331027538.tcb.qcloud.la/dialog_img_btn2.png");
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
  text-align: center;
}

.my-tip-tt {
  width: 142px;
  height: 45px;
  position: relative;
  top: 30px;
  background-image: url("https://7869-xiaofang-2g1dlrqbc66e0f24-1331027538.tcb.qcloud.la/dialog_img_title1.png");
  background-repeat: no-repeat;
  background-position: center;
  background-size: contain;
  text-align: center;
}
</style>